/*
 * @Author: your name
 * @Date: 2020-12-24 09:50:12
 * @LastEditTime: 2021-03-11 10:23:50
 * @LastEditors: your name
 * @Description: In User Settings Edit
 * @FilePath: \blog\model\user.js
 */
// 用户集合
const mongoose = require('mongoose')
const bcrypt = require('bcrypt')
const Joi = require('joi');
const userSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
    minlength: 2,
    maxlength: 20
  },
  email: {
    type: String,
    //保证邮箱地址不重复
    unique: true,
  },
  password: {
    type: String,
    required: true
  },
  role: {
    type: String,
    required: true
  },
  //0启用，1禁用
  state: {
    type: Number,
    default: 0
  }
})
const User = mongoose.model('User', userSchema)
async function createUser() {
  const salt = await bcrypt.genSalt(10)
  const pass = await bcrypt.hash('123456', salt)
  const user = await User.create({
    username: 'itemheima',
    email: '2227597587@qq.com',
    password: pass,
    role: 'admin',
    state: 0
  })
}
// createUser()
// User.create({
//     username: 'itemheima',
//     email: '2227597587@qq.com',
//     password: '123456',
//     role: 'admin',
//     state: 0
// }).then(() => {
//     console.log('创建成功')
// }).catch((err) => {
//     console.log(err)
// })

//验证用户信息
const validateUser = user => {
  //定义验证规则
  const Schema = {
    username: Joi.string().min(2).max(12).required().error(new Error('用户名不符合验证规则')),
    email: Joi.string().email().required().error(new Error('邮箱格式不符合')),
    password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/).required().error(new Error('密码格式不符合')),
    role: Joi.string().valid('normal', 'admin').required().error(new Error('角色值非法')),
    state: Joi.number().valid(0, 1).required().error(new Error('状态值非法'))
  }
  //实施验证
  return Joi.validate(user, Schema)
}
//将用户集合作为模块成员进行导出
module.exports = {
  User,
  validateUser
}